#include "simple_client.hpp"

SimpleClient::SimpleClient(/* args */)
{
}

SimpleClient::~SimpleClient()
{
}

std::string SimpleClient::request(bool& is_success)
{
    CommonData request;
    is_success = false;
    if (this->request_writer_->write(static_cast<void*>(&request), this->_listener.write_params)){
        // std::cout << "client 写数据" << std::endl;
        // 如果数据写成功就等待回复
        std::unique_lock<std::mutex> lock(this->_listener.reception_mutex);
        // this->_listener.reception_cv.wait(lock, [&]() {
        //     return this->_listener.received_replay;
        // });
        auto res = this->_listener.reception_cv.wait_for(lock, std::chrono::seconds(1));
        if (res == std::cv_status::no_timeout) {
            is_success = true;
            return this->_listener.response;
        }
    }
    is_success = false;
    return this->_listener.response;
}


int main(int argc, char const *argv[])
{
    uint64_t success_counter = 0;

    SimpleClient client;
    auto res = client.init();
    if (!res) {
        std::cout<< "error" << std::endl;
        return 0;
    }
    while (true)
    {
        bool is_success = false;
        auto res = client.request(is_success);
        if (is_success){
            success_counter++;
            std::cout << "simple service recv response " << res << " success counter = " << success_counter << std::endl;
        } else {
            std::cout << "error request" << std::endl;
        }
        // std::this_thread::sleep_for(std::chrono::seconds(1));    
    }
    
    return 0;
}
